#include <iostream>
#include <websocketpp/server.hpp>
#include <websocketpp/config/asio_no_tls.hpp>

typedef websocketpp::server<websocketpp::config::asio> websocketServer;

void httpHandler(websocketServer* svr, websocketpp::connection_hdl hdl)
{
    websocketServer::connection_ptr conn = svr->get_con_from_hdl(hdl);
    websocketpp::http::parser::request req = conn->get_request();
    std::cout << req.get_method().c_str() << std::endl;
    std::cout << req.get_uri().c_str() << std::endl;
    std::stringstream ss;
    ss << "<!doctype html><html><head>"
    << "<title>hello websocket</title><body>"
    << "<h1>hello websocketpp</h1>"
    << "</body></head></html>";

    conn->set_body(ss.str());
    conn->set_status(websocketpp::http::status_code::ok);
}

void OpenHandler(websocketServer* svr, websocketpp::connection_hdl hdl)
{
    std::cout << "websocket open" << std::endl;

    svr->send(hdl, "nihao", websocketpp::frame::opcode::text);
}

void CloseHandler(websocketServer* svr, websocketpp::connection_hdl hdl)
{
    std::cout << "websocket close" << std::endl;
}

void messageHandler(websocketServer* svr, websocketpp::connection_hdl hdl,  \
                    websocketServer::message_ptr msg)
{
    std::string s("client say:");
    s += msg->get_payload();
    std::cout << s << std::endl;
    svr->send(hdl, s, websocketpp::frame::opcode::text);
}

int main()
{
    //实例化server对象
    websocketServer svr;
    //设置日志
    svr.set_access_channels(websocketpp::log::alevel::none);
    //初始化asio
    svr.init_asio();
    svr.set_reuse_addr(true);
    //注册回调函数
    svr.set_http_handler(bind(httpHandler, &svr, std::placeholders::_1));
    svr.set_open_handler(bind(OpenHandler, &svr, std::placeholders::_1));
    svr.set_close_handler(bind(CloseHandler, &svr, std::placeholders::_1));
    svr.set_message_handler(bind(messageHandler, &svr, std::placeholders::_1, std::placeholders::_2));

    //bind端口
    svr.listen(8080);
    //接收链接
    svr.start_accept();
    //启动服务
    svr.run();

    return 0;
}